﻿using System;
using System.Collections.Generic;
using System.Linq;
using _5E.Infrastructure.Querying;
using _5E.Infrastructure.String;
using _5E.Infrastructure.UnitOfWork;
using WholesaleOnline.Contract;
using WholesaleOnline.DataContract.Messaging;
using WholesaleOnline.Model;
using WholesaleOnline.Model.Repository;

namespace WholesaleOnline.Service.Services
{
    public class AccountService : IAccountService
    {
        private IAccountRepository m_accountRepository = null;
        private IUnitOfWork m_uow = null;

        public AccountService(IAccountRepository accountRepository, IUnitOfWork uow)
        {
            m_accountRepository = accountRepository;
            m_uow = uow;
        }

        public LoginResponse Login(LoginRequest request)
        {
            LoginResponse response = new LoginResponse();
            try
            {
                Query accountQuery = new Query();
                accountQuery.Add(Criterion.Create<WoAccount>(a => a.Name, CriteriaOperator.Eq, request.AccountName));
                IEnumerable<WoAccount> accounts = m_accountRepository.FindBy(accountQuery);

                WoAccount account = 0 < accounts.Count() ? accounts.First() : new NullAccount();
                if (account.CheckPassword(request.AccountPassword))
                {
                    if (string.IsNullOrEmpty(account.BcryptPwd))
                    {
                        account.BcryptPwd = request.AccountPassword.ToBCrypt();
                        m_accountRepository.Save(account);
                        m_uow.Comit();
                    }
                    response.UserType = account.Type;
                    response.LoginId = account.Id;
                    response.Success = true;
                }
                else
                {
                    response.Message = "用户名或者密码不正确!";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return response;
        }
    }
}
